package com.example.arithmeticleetcode.learnArithmeticExercise;

import com.example.arithmeticleetcode.learnArithmetic.ArrayList;
import com.example.arithmeticleetcode.learnArithmetic.List;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2020-08-11 15:47
 **/
public class LinkedListExercise01 {

    public static void main(String[] args) {

    }

    public ListNode reverseList(ListNode head) {
        //递归
//        if (head == null || head.next == null) return head;
//        ListNode newHead = reverseList(head);
//        head.next.next = head;
//        head.next = null;
//        return newHead;

        ListNode newHead = null;
        while (head != null) {
            ListNode temp = head.next;
            head.next = newHead;
            newHead = head;
            head = temp;
        }
        return newHead;
    }

    public static boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) return false;
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null) {

            if (slow ==  fast) return true;

            slow = slow.next;
            fast = fast.next.next;
        }
        return false;
    }

    //203. 移除链表元素
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return null;
        }
        while (head != null && head.val == val) {
            head = head.next;
        }
        ListNode curr = head;
        ListNode prev = curr;
        while (curr != null) {
            if (curr.val == val) {
                prev.next = curr.next;
            } else {
                prev = curr;
            }
            curr = curr.next;
        }
        return head;
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}